﻿#include "tm_rectitem.h"
#include <QDebug>
#include <QGraphicsColorizeEffect>
#include <QTextBlockFormat>
#include <QTextCursor>


TM_RectItem::TM_RectItem(qreal PointWidth, qreal PointHeight,qreal Radius,QString text,bool move)
    : QGraphicsItem()
{
    if(Radius > 0)
    {
        m_X = -Radius;
        m_Y = -Radius;
        m_W = Radius*2;
        m_H = Radius*2;
        m_radius = Radius;
    }
    else
    {
        m_W = PointWidth;
        m_H = PointHeight;
        m_X = -PointWidth/2;
        m_Y = -PointHeight/2;
        m_radius = 0;
    }
    m_Text = text;
    this->setFlags(QGraphicsItem::ItemIsMovable
                   | QGraphicsItem::ItemIsSelectable
                   | QGraphicsItem::ItemIsFocusable);

    this->setFlag(QGraphicsItem::ItemIsMovable,move);
    this->setFlag(QGraphicsItem::ItemIsSelectable,true);

    setZValue(2);

    // QGraphicsColorizeEffect *colorizeEffect = new QGraphicsColorizeEffect();
    // colorizeEffect->setColor(Qt::transparent); // 设置颜色为透明
    // colorizeEffect->setStrength(0.3); // 设置透明度强度 (0.0 完全不透明, 1.0 完全透明)
    // this->setGraphicsEffect(colorizeEffect);

}


QRectF TM_RectItem::boundingRect() const
{
    return QRectF(m_X,m_Y,m_W,m_H);
}

void TM_RectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->setBrush(QBrush(QColor(255,255,0,100)));
    painter->setPen(QPen(QColor(255,255,0,150),0)); // 设置边框颜色
    if(m_Text.startsWith("CP"))
    {
        painter->setBrush(QBrush(QColor(0,255,255,100)));
        painter->setPen(QPen(QColor(0,255,255,100),0));
    }

    if(m_radius > 0)
        painter->drawEllipse(m_X,m_Y,m_W,m_H);
    else
        painter->drawRect(m_X,m_Y,m_W,m_H);

    painter->setBrush(QBrush(Qt::red));
    QPoint point[3] = {QPoint(m_W/2,0),QPoint(m_W/2-(m_W/6),-(m_W/6)),QPoint(m_W/2-(m_W/6),(m_W/6))};
    painter->drawConvexPolygon(point,3);

    painter->setPen(QColor(255,2,2,255));

    // 设置画笔和文字格式
    QFont font;
    font.setPointSize(m_H/4);
    font.setFamily("Microsoft New Tai Lue");
    font.setBold(true);
    font.setLetterSpacing(QFont::AbsoluteSpacing,0.1);//设置字间距为100像素
    painter->setFont(font);
    painter->setPen(Qt::black); // 设置画笔颜色为蓝色
    // 绘制文字
    QFontMetrics metrics = painter->fontMetrics();
    metrics.boundingRect(m_Text);
    painter->rotate(-this->rotation());
    painter->drawText(-metrics.boundingRect(m_Text).width()/2-2,
                        -metrics.boundingRect(m_Text).height()/2-2,
                        metrics.boundingRect(m_Text).width()+4,
                        metrics.boundingRect(m_Text).height()+4,
                        Qt::AlignCenter, m_Text);

}



